package com.zxh.blog.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.zxh.blog.MainActivity
import com.zxh.blog.R
import com.zxh.blog.bean.LoginResponse
import com.zxh.blog.bean.ResponseJson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException

@SuppressLint("CustomSplashScreen")
class SplashActivity : AppCompatActivity() {

    private lateinit var skipButton: Button

    private var countdownTimer: CountDownTimer? = null

    // 搜索功能用到的token
    private var mToken = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        ImmersionBar.with(this)
            .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
            .init()

        // 获取搜索用到的token,存到sp
        getTokenByOkhttp()

        skipButton = findViewById(R.id.skip_button)

        // 设置跳过按钮点击事件
        skipButton.setOnClickListener {
            // 结束倒计时
            countdownTimer?.cancel()

            // 跳转到首页或其他目标页面
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }

        // 开始倒计时，倒计时时间为3秒，每秒更新一次倒计时数字
        countdownTimer = object : CountDownTimer(5000, 1000) {
            @SuppressLint("StringFormatInvalid")
            override fun onTick(millisUntilFinished: Long) {
                val seconds = (millisUntilFinished / 1000).toInt()
                skipButton.text = getString(R.string.skip_button, seconds)
            }

            override fun onFinish() {
                // 倒计时结束后自动跳转到首页或其他目标页面
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                finish()
            }
        }.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        val sp = getSharedPreferences("search_token", Context.MODE_PRIVATE)
        sp.edit().putString("token",mToken).apply()
    }


    /**
     *  从后端发请求获取 token
     */
    private fun getTokenByOkhttp() {
        val mJSON = "application/json".toMediaType()
        val url = "http://43.140.201.43:8989/user/login"
        val map = mutableMapOf<String, String>()
        map["username"] = "享乐吧"
        map["password"] = "123456"
        val json = Gson().toJson(map)
        val client = OkHttpClient()
        // 创建JSON格式的请求体
        val jsonRequestBody = json.toRequestBody(mJSON)
        // 创建POST请求
        val request = Request.Builder()
            .url(url)
            .post(jsonRequestBody)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body?.string()
                if (responseData != null) {
                    val gson = Gson()
                    val typeToken = object : TypeToken<ResponseJson<LoginResponse>>() {}.type
                    val jsonResponse: ResponseJson<LoginResponse> = gson.fromJson(responseData, typeToken)
                    mToken = jsonResponse.data?.token.toString()
                }
            }
            override fun onFailure(call: Call, e: IOException) {}
        })
    }
}